import 'package:aio/aio.dart';
import 'package:app/src/ui/route/worksdo/type16_material_requisition/public/acom/ui_material_form.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/model/submit_model.dart';
import 'package:app/src/manager/audit_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/image/ui_image_upload.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../../http/model/material_requisition_model.dart';
import '../../../works/public/review_submitted.dart';

///审核提交
class ReviewSubmittedStateful2 extends StatefulWidget {
  //是否提交
  var hasSubmit = true;

  //是否包含保存
  var hasSave = false;

  //什么操作都没有；只有一个返回按钮。
  var onlyBack = false;

  //数据
  AppHttpResult<String, String>? mDatas;

  //提交之前回调,用于提交参数SubData赋值。
  ResponseCallbackWithT<SubData>? _callbackWithT = null;

  //提交前；用于验证数据。
  ResponseCallbackWithBoolResultII? _callbackWithBoolResultII = null;

  ReviewSubmittedStateful2(this.mDatas,
      {bool? hasSave = false,
      bool? hasSubmit = true,
      bool? onlyBack = false,
      ResponseCallbackWithT<SubData>? callbackWithT = null,
      ResponseCallbackWithBoolResultII? callbackWithBoolResult = null}) {
    this.hasSave = hasSave ?? false;
    this.hasSubmit = hasSubmit ?? true;
    this.onlyBack = onlyBack ?? false;
    this._callbackWithT = callbackWithT;
    this._callbackWithBoolResultII = callbackWithBoolResult;
  }

  @override
  _State createState() => _State();
}

class _State extends State<ReviewSubmittedStateful2> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    presenter?.mDatas = widget?.mDatas;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "review_submitted.dart"); //fixme 不在审核详情页面。
    UiMaterialForm.clearTextSelection(); //fixme 清除文本焦点位置
  }

  @override
  Widget build(BuildContext context) {
    // AuditManager.setDetailsWithAuto(
    //     true, "review_submitted.dart"); //fixme 当前在审核详情页面。现在需求任然需要显示通知信息。。
    return _body(context);
  }

  Widget _body(BuildContext context) {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      presenter.setStateBody = setState;
      List<Widget> children = [];
      var topMargin = 16.0;
      if (widget.onlyBack) {
        ///fixme 什么操作都没有，只有一个返回按钮。
        var row = Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                child: MaterialButton(
              onPressed: () {
                AppRouteHelper.pop(context);
              },
              color: ColorUtils.parseColor("#8F97AC"),
              textColor: Colors.white,
              padding: EdgeInsets.all(15),
              elevation: 0,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(8),
                      bottomLeft: Radius.circular(8),
                      topRight: Radius.circular(8),
                      bottomRight: Radius.circular(8))),
              child: Text(AppStrings.of(context).ReturnsList),
            ))
          ],
        );
        children.add(row);
      } else {
        //方向箭头
        // children.add(_arrowState(context));
        //选择状态
        children.add(_auditState(context));
        //审核意见
        // children.add(_auditOpinion(context));
        //提交审核
        // var submitName = AppStrings.of(context).SubmitAudit; //提交审核
        // if (AuditManager.IsApproval) {
        //   submitName = AppStrings.of(context).Theapproved; //已审核
        // }

        var submitName = AppStrings.of(context).Complete; //完成
        var SubmitAudit = MaterialButton(
          onPressed: () {
            // if (!AuditManager.IsApproval) {
            //   var b = true;
            //   if (widget._callbackWithBoolResultII != null) {
            //     var b2 = widget._callbackWithBoolResultII
            //         ?.call(); //fixme 提交之前验证数据格式。
            //     if (b2 != null) {
            //       b = b2;
            //     }
            //   }
            //   if (b) {
            //     presenter?.contractapply(context, widget._callbackWithT);
            //   }
            // }
            var b = true;
            if (widget._callbackWithBoolResultII != null) {
              var b2 =
                  widget._callbackWithBoolResultII?.call(); //fixme 提交之前验证数据格式。
              if (b2 != null) {
                b = b2;
              }
            }
            if (b) {
              presenter?.contractapply(context, widget._callbackWithT);
            }
          },
          color: ColorUtils.parseColor("#5985F0"),
          textColor: Colors.white,
          padding: EdgeInsets.all(15),
          elevation: 0,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(8), bottomLeft: Radius.circular(8))),
          child: Text(submitName),
        );
        //返回列表
        var ReturnsList = MaterialButton(
          onPressed: () {
            AppRouteHelper.pop(context);
          },
          color: ColorUtils.parseColor("#8F97AC"),
          textColor: Colors.white,
          padding: EdgeInsets.all(15),
          elevation: 0,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  topRight: Radius.circular(8),
                  bottomRight: Radius.circular(8))),
          child: Text(AppStrings.of(context).ReturnsList),
        );
        var row = Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(child: SubmitAudit),
            Expanded(child: ReturnsList)
          ],
        );
        children.add(row);
      }
      return Container(
        padding: EdgeInsets.only(left: 8, right: 8, top: topMargin, bottom: 16),
        child: Column(
          children: children,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Colors.black, blurRadius: 10, offset: Offset(0, 10))
          ],
        ),
      );
    });
  }

  var _isOpen = false;

  ///方向箭头
  Widget _arrowState(BuildContext context) {
    var imagePath = ImagePathUtils.getPathWithImageArrow("ic_011_top.png");
    if (_isOpen) {
      imagePath = ImagePathUtils.getPathWithImageArrow("ic_011_bottom.png");
    }
    var center = Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(top: 12, bottom: 12, left: 100, right: 100),
      child: Image.asset(
        imagePath,
        height: 16,
      ),
    );
    return InkWell(
      child: center,
      onTap: () {
        presenter?.setStateBody!(() {
          _isOpen = !_isOpen;
        });
      },
    );
  }

  ///审核状态选择
  Widget _auditState(BuildContext context) {
    return StatefulBuilder(builder: (context, setState) {
      List<Widget> children = [];
      //提交
      if (widget.hasSubmit) {
        var agree = Radio(
          value: _status_submit,
          //value 单选框的值;是泛型
          groupValue: presenter._status,
          //groupValue 选中的值，如果 value 和 groupValue 相等。就是选中状态。
          toggleable: true,
          //toggleable: true 即可以选中，也可以取消；false（默认） 点击时只能选中，不能取消。只能点击其他控件取消。
          onChanged: (value) {
            //点击时状态改变时回调。
            //print('value:$value'); //返回的就是点击的 value 的值。
            if (value != null) {
              setState(() {
                presenter._status = value.toString();
              });
            }
          },
          activeColor: Colors.blueAccent,
        );
        children.add(agree);
        children.add(Text(AppStrings.of(context).Submit + "  "));
      }
      //保存
      if (widget.hasSave) {
        var agree = Radio(
          value: _status_save,
          //value 单选框的值;是泛型
          groupValue: presenter._status,
          //groupValue 选中的值，如果 value 和 groupValue 相等。就是选中状态。
          toggleable: true,
          //toggleable: true 即可以选中，也可以取消；false（默认） 点击时只能选中，不能取消。只能点击其他控件取消。
          onChanged: (value) {
            //点击时状态改变时回调。
            //print('value:$value'); //返回的就是点击的 value 的值。
            if (value != null) {
              setState(() {
                presenter._status = value.toString();
              });
            }
          },
          activeColor: Colors.blueAccent,
        );
        children.add(agree);
        children.add(Text(AppStrings.of(context).save + "  "));
      }
      var row = Row(
        children: children,
      );
      return Container(
        child: row,
        margin: EdgeInsets.only(top: 10, bottom: 0),
      );
    });
  }

  ///审核意见
  Widget _auditOpinion(BuildContext context) {
    if (!_isOpen) {
      return AppUi.getEmptyView();
    }
    //软键盘数量类型
    if (presenter?.textEditingController == null) {
      presenter?.textEditingController =
          TextUtils.setTextEditingController(text: presenter?.auditOpinion);
    }
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        var textField = TextField(
          textAlign: TextAlign.start,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.auditOpinion = value;
            });
          },
          autofocus: false,
          //autofocus true 自动聚焦，软键盘会自动弹出。
          controller: presenter?.textEditingController,
          maxLines: 4,
          decoration: InputDecoration(
              isCollapsed: true,
              hintText: AppStrings.of(context).PleaseInputOpinion,
              contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
              border: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.black12, width: 1.5),
                  borderRadius: BorderRadius.all(Radius.circular(5.0))),
              focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.blueAccent, width: 1.5),
                  borderRadius: BorderRadius.all(Radius.circular(5.0)))),
        );
        //通过SizedBox设置文本框的高度
        return Container(
          alignment: Alignment.topCenter,
          child: textField,
          height: 110,
        );
      },
    );
  }
}

final String _status_submit = "1"; //提交
final String _status_save = "0"; //保存

class _Presenter {
  ///body视图状态
  StateSetter? setStateBody;

  TextEditingController? textEditingController = null;

  //审核状态
  var _status = _status_submit;

  //审核意见
  String auditOpinion = "";

  //数据
  AppHttpResult<String, String>? mDatas;

  //提交数据
  SubData? _subData = null;

  //退回至
  backTo(BuildContext context, StateSetter setState) {
    if (mDatas != null) {
      AppDialog.showDialogWithRollerPicker<NodeShow>(context,
              datas: mDatas?.BackToUserInfoList, data: mDatas?.BackToUserInfo)
          .then((value) {
        //print('=====================${value?.FactoryName}');
        if (value != null) {
          setState(() {
            mDatas?.BackToUserInfo = value;
          });
        }
      });
    }
  }

  ///提交审核
  contractapply(
      BuildContext context, ResponseCallbackWithT<SubData>? _callbackWithT) {
    AuditManager.getAuditManager().setDetailsWithAuto(true,
        "review_submitted2.dart"); //fixme 在审核详情页面,正在提交的时候，不要显示通知信息。没有提交的时候，还是要显示的。
    if (_subData == null) {
      _subData = SubData();
    }
    _callbackWithT?.call(_subData!); //fixme 提交之前回调，用于提交参数赋值。
    //fixme 先上传图片
    UiImageUpLoad.syspicupload(context, (value) {
      _subData?.pics = value; //fixme 图片地址
      //fixme 审核提交
      MaterialModel.SavePurDemand(context, true, _status,
              pics: value, subData: _subData)
          ?.then((value) {
        isRefreshPreviousAppList = true;
        if (value.isSuccessForCode()) {
          if (value.MsgDetail != null && value.MsgDetail!.length > 0) {
            Toast.showSuccess(
                value?.MsgDetail, context); //fixme 提交成功,优先提示服务器提示信息。
            _subData?.purDemand?.FilePatch =
                _subData?.purDemand?.FilePatchOld; //fixme 提交失败，图片复原。
          } else {
            Toast.showSuccess(
                AppStrings.of(context).SubmitSuccessfully, context); //提交成功
          }
          UiImageUpLoad.clear(); //提交成功，清除本地图片
          AppRouteHelper.pop(context, true); //关闭当前审核页面
          AuditManager.getAuditManager().setDetailsWithAuto(
              false, "review_submitted2.dart"); //fixme 审核详情页面提交结束，可以显示通知信息。
        } else {
          //提示错误信息
          AppDialog.showDialogWithInfo(context, content: value.MsgDetail);
          AuditManager.getAuditManager().setDetailsWithAuto(
              false, "review_submitted2.dart"); //fixme 审核详情页面提交结束，可以显示通知信息。
        }
      });
    });
  }
}
